package com.liu.netty.service;

import com.liu.netty.dao.DriverDao;
import com.liu.netty.dao.SenorDao;
import com.liu.netty.entity.Driver;
import com.liu.netty.entity.Senor;
import com.liu.netty.pojo.Message;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import util.IdWorker;

import javax.transaction.Transactional;
import java.util.Date;


@Service
@Transactional
public class SenorService {


    @Autowired
    private SenorDao senorDao;
    @Autowired
    private DriverDao driverDao;

    @Autowired
    private IdWorker idWorker;


    public boolean addSenor(Senor senor,String objectAddress){
        senor.setId(idWorker.nextId()+"");
        senor.setDateTime(new Date());
        Driver driver = driverDao.findByObjectAddress(objectAddress);
        senor.setDriver(driver);
        senorDao.save(senor);
        return  true;
    }


    public boolean upSenorFromClient(Message message) {
        Senor senor = new Senor();
        BeanUtils.copyProperties(message,senor);
        addSenor(senor,message.getObjectAddress());
     return  true;
    }

    public Page<Senor> findPageSenor(Integer page, Integer rows) {
        if(rows == null){
           rows=10;
        }
        if( page== null){
            page=1;
        }
        Pageable pageable = PageRequest.of(page-1,rows);
        return  senorDao.findAll(pageable);

    }
}
